package cn.mdmbct.douyin.common.proxy;

import cn.mdmbct.douyin.common.executor.ServiceExecutor;
import cn.mdmbct.douyin.common.proxy.invoker.ServiceMethodInvoker;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author mdmbct  mdmbct@outlook.com
 * @date 5/9/2021 10:10 PM
 * @modified mdmbct
 * @since 1.0
 */
public class ServiceProxyFactory<T> {

    private final Class<T> serviceInterface;

    private final Map<Method, ServiceMethodInvoker<T>> methodCache;

    public ServiceProxyFactory(Class<T> serviceInterface) {
        this.serviceInterface = serviceInterface;
        this.methodCache = new ConcurrentHashMap<>();

    }

    public T create(ServiceExecutor serviceExecutor) {
        ServiceProxy<T> serviceProxy = new ServiceProxy<T>(serviceExecutor, methodCache);
        return create(serviceProxy);
    }

    @SuppressWarnings("unchecked")
    public T create(ServiceProxy<T> serviceProxy) {
        return (T) Proxy.newProxyInstance(serviceInterface.getClassLoader(), new Class[]{serviceInterface}, serviceProxy);
    }


}
